<template>
  <div class="record-management-container">
    <!-- 页面头部 -->
    <div class="record-header">
      <div class="header-content">
        <div class="ancient-title">值班记录管理</div>
        <div class="header-subtitle">阴曹地府 · 出勤统计与绩效评估</div>
      </div>
    </div>

    <!-- 路由信息 -->
    <div class="route-info">
      <a-breadcrumb>
        <a-breadcrumb-item
          ><router-link to="/management"><ApartmentOutlined />机构管理</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item
          ><router-link to="/management/duty-schedule"><ScheduleOutlined />值班排班系统</router-link></a-breadcrumb-item
        >
        <a-breadcrumb-item><FileTextOutlined />{{ $route.meta.title }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <!-- 统计概览 -->
    <div class="stats-section">
      <a-row :gutter="[20, 20]" class="stats-grid">
        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card primary-stat">
            <div class="stat-icon"><CheckCircleOutlined /></div>
            <div class="stat-content">
              <div class="stat-title">本月出勤</div>
              <div class="stat-value">{{ recordStats.monthlyAttendance }}%</div>
              <div class="stat-label">平均出勤率</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card judgment-stat">
            <div class="stat-icon"><FileTextOutlined /></div>
            <div class="stat-content">
              <div class="stat-title">总记录数</div>
              <div class="stat-value">{{ recordStats.totalRecords }}</div>
              <div class="stat-label">条记录</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card pending-stat">
            <div class="stat-icon"><ExclamationCircleOutlined /></div>
            <div class="stat-content">
              <div class="stat-title">异常记录</div>
              <div class="stat-value">{{ recordStats.abnormalRecords }}</div>
              <div class="stat-label">需处理</div>
            </div>
          </div>
        </a-col>
        <a-col :xs="24" :sm="12" :xl="6">
          <div class="stat-card online-stat">
            <div class="stat-icon"><TrophyOutlined /></div>
            <div class="stat-content">
              <div class="stat-title">满勤人员</div>
              <div class="stat-value">{{ recordStats.perfectAttendance }}</div>
              <div class="stat-label">人</div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <a-row :gutter="24">
      <!-- 左侧：记录列表 -->
      <a-col :xs="24" :lg="16">
        <a-card title="值班记录" :bordered="false">
          <template #extra>
            <a-space>
              <a-button type="primary" @click="showAddRecordModal"> <PlusOutlined />补录记录 </a-button>
              <a-button @click="exportRecords"> <ExportOutlined />导出记录 </a-button>
            </a-space>
          </template>

          <!-- 筛选区域 -->
          <div class="filter-section">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-date-picker v-model:value="filterDate" placeholder="选择日期" style="width: 100%" />
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterDepartment" placeholder="部门筛选" style="width: 100%" allow-clear>
                  <a-select-option value="">全部部门</a-select-option>
                  <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.name">
                    {{ dept.name }}
                  </a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-select v-model:value="filterStatus" placeholder="状态筛选" style="width: 100%" allow-clear>
                  <a-select-option value="">全部状态</a-select-option>
                  <a-select-option value="present">正常出勤</a-select-option>
                  <a-select-option value="late">迟到</a-select-option>
                  <a-select-option value="early-leave">早退</a-select-option>
                  <a-select-option value="absent">缺勤</a-select-option>
                </a-select>
              </a-col>
              <a-col :span="6">
                <a-input-search v-model:value="searchText" placeholder="搜索人员" @search="handleSearch" />
              </a-col>
            </a-row>
          </div>

          <!-- 记录表格 -->
          <a-table :columns="recordColumns" :data-source="filteredRecords" :pagination="{ pageSize: 10 }" row-key="id">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
              </template>
              <template v-if="column.key === 'duration'"> {{ calculateDuration(record.startTime, record.endTime) }}小时 </template>
              <template v-if="column.key === 'actions'">
                <a-space>
                  <a-button type="link" size="small" @click="viewRecord(record)"> <EyeOutlined />查看 </a-button>
                  <a-button type="link" size="small" @click="editRecord(record)"> <EditOutlined />编辑 </a-button>
                  <a-popconfirm title="确定删除此记录吗？" @confirm="deleteRecord(record)">
                    <a-button type="link" size="small" danger> <DeleteOutlined />删除 </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>

      <!-- 右侧：统计图表 -->
      <a-col :xs="24" :lg="8">
        <a-space direction="vertical" size="large" style="width: 100%">
          <!-- 出勤率趋势 -->
          <a-card title="出勤率趋势" size="small" :bordered="false">
            <div class="attendance-trend">
              <div v-for="trend in attendanceTrend" :key="trend.month" class="trend-item">
                <div class="trend-info">
                  <span class="trend-month">{{ trend.month }}</span>
                  <span class="trend-rate">{{ trend.rate }}%</span>
                </div>
                <div class="trend-bar">
                  <div class="trend-progress" :style="{ width: trend.rate + '%' }"></div>
                </div>
              </div>
            </div>
          </a-card>

          <!-- 部门排名 -->
          <a-card title="部门出勤排名" size="small" :bordered="false">
            <div class="department-ranking">
              <div v-for="(dept, index) in departmentRanking" :key="dept.id" class="ranking-item">
                <div class="ranking-position">{{ index + 1 }}</div>
                <div class="ranking-info">
                  <div class="dept-name">{{ dept.name }}</div>
                  <div class="dept-rate">{{ dept.attendanceRate }}%</div>
                </div>
                <div class="ranking-medal" v-if="index < 3">
                  <TrophyOutlined :style="{ color: getMedalColor(index) }" />
                </div>
              </div>
            </div>
          </a-card>

          <!-- 异常统计 -->
          <a-card title="异常统计" size="small" :bordered="false">
            <div class="anomaly-stats">
              <div class="anomaly-item">
                <span class="anomaly-label">迟到次数：</span>
                <span class="anomaly-value">{{ anomalyStats.late }}次</span>
              </div>
              <div class="anomaly-item">
                <span class="anomaly-label">早退次数：</span>
                <span class="anomaly-value">{{ anomalyStats.earlyLeave }}次</span>
              </div>
              <div class="anomaly-item">
                <span class="anomaly-label">缺勤次数：</span>
                <span class="anomaly-value">{{ anomalyStats.absent }}次</span>
              </div>
              <div class="anomaly-item">
                <span class="anomaly-label">请假次数：</span>
                <span class="anomaly-value">{{ anomalyStats.leave }}次</span>
              </div>
            </div>
          </a-card>

          <!-- 快速操作 -->
          <a-card title="快速操作" size="small" :bordered="false">
            <div class="quick-actions">
              <a-button block @click="generateReport" style="margin-bottom: 8px"> <FileTextOutlined />生成报表 </a-button>
              <a-button block @click="attendanceAnalysis" style="margin-bottom: 8px"> <BarChartOutlined />出勤分析 </a-button>
              <a-button block @click="performanceEvaluation"> <TrophyOutlined />绩效评估 </a-button>
            </div>
          </a-card>
        </a-space>
      </a-col>
    </a-row>

    <!-- 补录记录弹窗 -->
    <a-modal v-model:open="addRecordModalVisible" title="补录值班记录" @ok="handleAddRecord" width="600px">
      <a-form ref="recordFormRef" :model="recordForm" :rules="recordRules" layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="值班人员" name="personnel">
              <a-input v-model:value="recordForm.personnel" placeholder="请输入人员姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所属部门" name="department">
              <a-select v-model:value="recordForm.department" placeholder="选择部门">
                <a-select-option v-for="dept in allDepartments" :key="dept.id" :value="dept.name">
                  {{ dept.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="值班日期" name="date">
              <a-date-picker v-model:value="recordForm.date" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="出勤状态" name="status">
              <a-select v-model:value="recordForm.status" placeholder="选择状态">
                <a-select-option value="present">正常出勤</a-select-option>
                <a-select-option value="late">迟到</a-select-option>
                <a-select-option value="early-leave">早退</a-select-option>
                <a-select-option value="absent">缺勤</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="开始时间" name="startTime">
              <a-time-picker v-model:value="recordForm.startTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" name="endTime">
              <a-time-picker v-model:value="recordForm.endTime" format="HH:mm" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注说明" name="note">
          <a-textarea v-model:value="recordForm.note" placeholder="记录相关说明" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  HomeOutlined,
  ApartmentOutlined,
  ScheduleOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  TrophyOutlined,
  PlusOutlined,
  ExportOutlined,
  EyeOutlined,
  EditOutlined,
  DeleteOutlined,
  BarChartOutlined
} from '@ant-design/icons-vue'

// 响应式数据
const searchText = ref('')
const filterDate = ref(null)
const filterDepartment = ref('')
const filterStatus = ref('')
const addRecordModalVisible = ref(false)
const recordFormRef = ref()

// 统计数据
const recordStats = reactive({
  monthlyAttendance: 96,
  totalRecords: 2580,
  abnormalRecords: 12,
  perfectAttendance: 45
})

// 部门数据
const allDepartments = ref([
  { id: 1, name: '第一殿秦广王府' },
  { id: 2, name: '第二殿楚江王府' },
  { id: 5, name: '第五殿阎罗王府' },
  { id: 10, name: '第十殿转轮王府' }
])

// 值班记录数据
const records = ref([
  {
    id: 1,
    personnel: '秦广王',
    department: '第一殿秦广王府',
    date: '2023-11-20',
    startTime: '08:00',
    endTime: '18:00',
    status: 'present',
    note: '正常值班'
  },
  {
    id: 2,
    personnel: '判官李明',
    department: '第一殿秦广王府',
    date: '2023-11-20',
    startTime: '08:15',
    endTime: '18:00',
    status: 'late',
    note: '迟到15分钟'
  },
  {
    id: 3,
    personnel: '阎罗王',
    department: '第五殿阎罗王府',
    date: '2023-11-20',
    startTime: '00:00',
    endTime: '24:00',
    status: 'present',
    note: '全天值班'
  }
])

// 表格列定义
const recordColumns = [
  { title: '人员', dataIndex: 'personnel', key: 'personnel' },
  { title: '部门', dataIndex: 'department', key: 'department' },
  { title: '日期', dataIndex: 'date', key: 'date' },
  { title: '开始时间', dataIndex: 'startTime', key: 'startTime' },
  { title: '结束时间', dataIndex: 'endTime', key: 'endTime' },
  { title: '工时', key: 'duration' },
  { title: '状态', key: 'status' },
  { title: '备注', dataIndex: 'note', key: 'note' },
  { title: '操作', key: 'actions' }
]

// 出勤趋势数据
const attendanceTrend = ref([
  { month: '9月', rate: 94 },
  { month: '10月', rate: 96 },
  { month: '11月', rate: 98 }
])

// 部门排名
const departmentRanking = ref([
  { id: 10, name: '第十殿', attendanceRate: 98 },
  { id: 5, name: '第五殿', attendanceRate: 96 },
  { id: 1, name: '第一殿', attendanceRate: 95 },
  { id: 2, name: '第二殿', attendanceRate: 93 }
])

// 异常统计
const anomalyStats = reactive({
  late: 15,
  earlyLeave: 8,
  absent: 3,
  leave: 12
})

// 表单数据
const recordForm = reactive({
  personnel: '',
  department: '',
  date: null,
  status: '',
  startTime: null,
  endTime: null,
  note: ''
})

// 表单验证规则
const recordRules = {
  personnel: [{ required: true, message: '请输入人员姓名', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 计算属性
const filteredRecords = computed(() => {
  let result = records.value

  if (filterDepartment.value) {
    result = result.filter((record) => record.department === filterDepartment.value)
  }

  if (filterStatus.value) {
    result = result.filter((record) => record.status === filterStatus.value)
  }

  if (searchText.value) {
    result = result.filter((record) => record.personnel.toLowerCase().includes(searchText.value.toLowerCase()))
  }

  return result
})

// 方法
const getStatusColor = (status) => {
  const colors = {
    present: 'green',
    late: 'orange',
    'early-leave': 'orange',
    absent: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    present: '正常出勤',
    late: '迟到',
    'early-leave': '早退',
    absent: '缺勤'
  }
  return texts[status] || status
}

const getMedalColor = (index) => {
  const colors = ['#ffd700', '#c0c0c0', '#cd7f32']
  return colors[index] || '#666'
}

const calculateDuration = (startTime, endTime) => {
  // 简单的时间计算示例
  if (!startTime || !endTime) return 0
  const start = new Date(`2023-01-01 ${startTime}`)
  const end = new Date(`2023-01-01 ${endTime}`)
  if (end < start) {
    end.setDate(end.getDate() + 1) // 跨日处理
  }
  return Math.round(((end - start) / (1000 * 60 * 60)) * 10) / 10
}

const showAddRecordModal = () => {
  Object.assign(recordForm, {
    personnel: '',
    department: '',
    date: null,
    status: '',
    startTime: null,
    endTime: null,
    note: ''
  })
  addRecordModalVisible.value = true
}

const handleAddRecord = async () => {
  try {
    await recordFormRef.value.validate()
    const newRecord = {
      id: Date.now(),
      ...recordForm,
      date: recordForm.date ? recordForm.date.format('YYYY-MM-DD') : '',
      startTime: recordForm.startTime ? recordForm.startTime.format('HH:mm') : '',
      endTime: recordForm.endTime ? recordForm.endTime.format('HH:mm') : ''
    }
    records.value.push(newRecord)
    message.success('记录补录成功')
    addRecordModalVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const viewRecord = (record) => {
  message.info(`查看记录: ${record.personnel}`)
}

const editRecord = (record) => {
  message.info(`编辑记录: ${record.personnel}`)
}

const deleteRecord = (record) => {
  const index = records.value.findIndex((r) => r.id === record.id)
  if (index > -1) {
    records.value.splice(index, 1)
    message.success('记录删除成功')
  }
}

const generateReport = () => {
  message.info('生成出勤报表功能开发中...')
}

const attendanceAnalysis = () => {
  message.info('出勤分析功能开发中...')
}

const performanceEvaluation = () => {
  message.info('绩效评估功能开发中...')
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const exportRecords = () => {
  message.info('记录导出功能开发中...')
}

onMounted(() => {
  // 页面加载时的初始化逻辑
})
</script>

<style lang="scss" scoped>
.record-management-container {
  padding: 24px;

  .record-header {
    text-align: center;
    margin-bottom: 32px;

    .header-content {
      .ancient-title {
        font-size: 32px;
        font-weight: bold;
        color: $secondary-color;
        margin-bottom: 8px;
        text-shadow: 0 0 20px rgba(212, 153, 10, 0.3);
      }

      .header-subtitle {
        font-size: 16px;
        color: $text-secondary;
        letter-spacing: 2px;
      }
    }
  }

  .route-info {
    margin-bottom: 24px;
    padding: 12px 16px;
    border-radius: 8px;
    backdrop-filter: blur(10px);
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .stats-section {
    margin-bottom: 32px;

    .stat-card {
      border-radius: 12px;
      padding: 24px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      border: 1px solid rgba(212, 153, 10, 0.2);
      transition: all 0.3s ease;
      display: flex;
      align-items: center;
      gap: 16px;

      .stat-icon {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        color: white;
      }

      .stat-content {
        flex: 1;

        .stat-title {
          font-size: 14px;
          color: $text-secondary;
          margin-bottom: 4px;
        }

        .stat-value {
          font-size: 28px;
          font-weight: bold;
          color: $primary-color;
          margin-bottom: 4px;
        }

        .stat-label {
          font-size: 12px;
          color: $text-secondary;
        }
      }

      &.primary-stat .stat-icon {
        background: linear-gradient(135deg, #52c41a, #73d13d);
      }

      &.judgment-stat .stat-icon {
        background: linear-gradient(135deg, #1890ff, #40a9ff);
      }

      &.pending-stat .stat-icon {
        background: linear-gradient(135deg, #fa8c16, #ffa940);
      }

      &.online-stat .stat-icon {
        background: linear-gradient(135deg, #722ed1, #9254de);
      }
    }
  }

  .filter-section {
    margin-bottom: 20px;
    padding: 16px;
    border-radius: 8px;
    border: 1px solid rgba(212, 153, 10, 0.2);
  }

  .attendance-trend {
    .trend-item {
      margin-bottom: 12px;

      .trend-info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 4px;
        font-size: 14px;

        .trend-month {
          color: $text-primary;
        }

        .trend-rate {
          color: $secondary-color;
          font-weight: bold;
        }
      }

      .trend-bar {
        height: 8px;
        background: #f0f0f0;
        border-radius: 4px;
        overflow: hidden;

        .trend-progress {
          height: 100%;
          background: linear-gradient(90deg, $secondary-color, #f0c674);
          transition: width 0.3s ease;
        }
      }
    }
  }

  .department-ranking {
    .ranking-item {
      display: flex;
      align-items: center;
      gap: 12px;
      padding: 8px 0;
      border-bottom: 1px solid rgba(212, 153, 10, 0.1);

      &:last-child {
        border-bottom: none;
      }

      .ranking-position {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background: rgba(212, 153, 10, 0.1);
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        color: $secondary-color;
      }

      .ranking-info {
        flex: 1;

        .dept-name {
          font-size: 14px;
          color: $text-primary;
          margin-bottom: 2px;
        }

        .dept-rate {
          font-size: 12px;
          color: $text-secondary;
        }
      }

      .ranking-medal {
        font-size: 16px;
      }
    }
  }

  .anomaly-stats {
    .anomaly-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 8px;

      .anomaly-label {
        color: $text-secondary;
        font-size: 14px;
      }

      .anomaly-value {
        color: $secondary-color;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }

  .quick-actions {
    .ant-btn {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      gap: 8px;
    }
  }

  :deep(.ant-card) {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(212, 153, 10, 0.2);
    border-radius: 12px;
  }

  :deep(.ant-card-head) {
    border-bottom: 1px solid rgba(212, 153, 10, 0.2);
  }

  :deep(.ant-table) {
    .ant-table-thead > tr > th {
      background: rgba(212, 153, 10, 0.1);
      color: $primary-color;
      font-weight: bold;
    }
  }
}
</style>
